package com.ytd.smartcanteen.weighting.devices;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.ytd.common.util.ByteUtil;
import com.ytd.common.util.LogUtil;
import com.ytd.smartcanteen.weighting.util.WeightConfig;

import java.io.File;
import java.io.IOException;

import android_serialport_api.SerialCallback;
import android_serialport_api.SerialPort;

/**
 * 扫描器管理类
 *
 * @author gaoguanchao
 * @since 2023/3/22 0022
 */
public class ScannerManager {
    private static final String TAG = "ScannerManager";
    /**
     * 恢复出厂设置
     */
    private static final String RESET_STR = "7E00080100D9804AAE";
    /**
     * 单点激活
     */
    private static final String SINGLE_STR = "7E0008010000F5CB23";
    /**
     * 单点激活
     */
    private static final String SINGLE_STR1 = "7E00080100020102DA";
    /**
     * 连续识别
     */
    private static final String CONTINUOUS_STR = "7E0008010000F6FB40";
    /**
     * 保存设置
     */
    private static final String SAVE_STR = "7E000901000000DEC8";
    private static final int READ_REFRESH = 888;

    private boolean mInit = false;

    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == READ_REFRESH) {
                mData = "";
                if (mCallback != null) {
                    mCallback.onClose();
                }
                LogUtil.d(TAG, "扫码：onClose");
            }
        }
    };

    private SerialPort mSerialPort = null;

    private String mData = "";

    private ScannerCallBack mCallback;

    private final SerialCallback mSerialCallback = new SerialCallback() {
        @Override
        public void onReadData(final String data) {
            mHandler.removeMessages(READ_REFRESH);
            if (!TextUtils.equals(mData, data.trim())) {
                if (!TextUtils.isEmpty(data.trim()) && mCallback != null) {
                    mData = data.trim();
                    LogUtil.d(TAG, "扫码：" + data.trim());
                    String scannerData = handleScannerData(mData);
                    mCallback.onScanner(scannerData);
                }
            }
            mHandler.sendEmptyMessageDelayed(READ_REFRESH, 1200);
        }
    };

    private String handleScannerData(String str) {
        if (TextUtils.isEmpty(str)) {
            return str;
        }
        if (str.length() > 7) {
            return str.substring(0, 7);
        }
        return str;
    }

    public void init() {
        try {
            String scannerPath = WeightConfig.getScannerPath();
            int scannerBit = WeightConfig.getScannerBit();
            LogUtil.d("ScannerManager init " + scannerPath + "  " + scannerBit);
            mSerialPort = new SerialPort(new File(scannerPath), scannerBit, mSerialCallback);
            mInit = true;
            LogUtil.d("ScannerManager init success");
        } catch (IOException e) {
            LogUtil.e("ScannerManager init Exception", e);
            mInit = false;
        }
    }

    public void setCallback(ScannerCallBack callback) {
        mCallback = callback;
    }

    public void release() {
        if (!mInit) {
            return;
        }
        mHandler.removeCallbacksAndMessages(null);
        mSerialPort.closePort();
        mSerialPort = null;
    }

    public void resetData() {
        mData = null;
    }

    private ScannerManager() {
    }

    public static ScannerManager getInstance() {
        return ManagerHolder.instance;
    }

    public void sendReset() {
        if (!mInit || mSerialPort == null) {
            return;
        }
        mSerialPort.send(ByteUtil.hexStr2bytes(RESET_STR));
    }

    public void sendSingle() {
        if (!mInit || mSerialPort == null) {
            return;
        }
        mSerialPort.send(ByteUtil.hexStr2bytes(SINGLE_STR));
        SystemClock.sleep(500);
        mSerialPort.send(ByteUtil.hexStr2bytes(SINGLE_STR1));
    }

    public void sendContinuous() {
        if (!mInit || mSerialPort == null) {
            return;
        }
        mSerialPort.send(ByteUtil.hexStr2bytes(CONTINUOUS_STR));
        SystemClock.sleep(500);
        mSerialPort.send(ByteUtil.hexStr2bytes(SAVE_STR));
    }

    private static class ManagerHolder {
        private static final ScannerManager instance = new ScannerManager();
    }

    public interface ScannerCallBack {
        void onScanner(String data);

        void onClose();
    }
}
